﻿using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        [DllImport("user32.dll")]
        public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);

        //protected override void OnStartup(StartupEventArgs e)
        //{
        //    Process currentProcess = Process.GetCurrentProcess(); //获取当前进程
        //    //获取当前运行程序完全限定名
        //    string currentFileName = currentProcess.MainModule.FileName;
        //    Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName);
        //    foreach (Process process in processes)
        //    {
        //        if (process.Id != currentProcess.Id)
        //        { //根据进程ID排除当前进程
        //            MessageBox.Show("系统已启动");
        //            IntPtr handle = process.MainWindowHandle;
        //            //将原进程显示在最前
        //            SwitchToThisWindow(handle, true);
        //            Application.Current.Shutdown();
        //            return;
        //        }
        //    }
        //    base.OnStartup(e);
        //}


        //protected override void OnStartup(StartupEventArgs e)
        //{
        //    bool createdNew;
        //    Mutex mutex = new Mutex(true, "ED4D324324242ERS", out createdNew); // 使用唯一的GUID作为互斥锁名称

        //    if (!createdNew)
        //    {
        //        var current = Process.GetCurrentProcess();
        //        var processes = Process.GetProcessesByName(current.ProcessName);

        //        var process = processes.FirstOrDefault(x => x.Id == current.Id);
        //        if (process != null)
        //        {
        //            IntPtr handle = process.MainWindowHandle;
        //            SwitchToThisWindow(handle, true);
        //        }
        //        Application.Current.Shutdown();
        //    }

        //    //正常启动
        //    base.OnStartup(e);
        //}

        protected override void OnStartup(StartupEventArgs e)
        {
            var instance = UniqueProcess.RunningInstance();
            if (instance != null)
            {
                UniqueProcess.HandleRunningInstance(instance);
                //关闭
                Application.Current.Shutdown();

                return;
            }

            //正常启动
            base.OnStartup(e);
        }
    }
}
